/*
Copyright 2022 TriggerMesh Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package reconciler

import (
	"strings"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// Stateful events related
const (
	LabelBridgeUsedByPrefix  = "flow.triggermesh.io/used-by."
	LabelValueBridgeDominant = "dominant"

	// Bridge identifier for stateful flows
	EnvBridgeID = "EVENTS_BRIDGE_IDENTIFIER"
)

// GetStatefulBridgeID returns the BridgeID based on an object metadata.
//
// All bridge components controlled by Triggerflow have labels informing their
// relation with the bridges they are part of. A component can only have one
// dominant bridge, which is the one it synchronizes with. This function uses
// that label to retrieve the bridge name and use it as unique ID.
func GetStatefulBridgeID(object metav1.Object) string {
	labels := object.GetLabels()

	for k, v := range labels {
		if strings.HasPrefix(k, LabelBridgeUsedByPrefix) && v == LabelValueBridgeDominant {
			return k[len(LabelBridgeUsedByPrefix):]
		}
	}

	return ""
}
